package com.cari.oa.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.validation.Valid;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.cari.oa.domain.AttachmentEntity;
import com.cari.oa.domain.CommentEntity;
import com.cari.oa.domain.MarketProjectEntity;
import com.cari.oa.domain.NotificationEntity;
import com.cari.oa.domain.ReqEntity;
import com.cari.oa.domain.ReqTypeEntity;
import com.cari.oa.domain.ReqUserRefEntity;
import com.cari.oa.domain.SysDictItemEntity;
import com.cari.oa.domain.SysUserEntity;
import com.cari.oa.service.AttachmentService;
import com.cari.oa.service.CommentService;
import com.cari.oa.service.MarketProjectService;
import com.cari.oa.service.NotificationService;
import com.cari.oa.service.ReqService;
import com.cari.oa.service.ReqTypeService;
import com.cari.oa.service.ReqUserRefService;
import com.cari.oa.service.SysDictItemService;
import com.cari.oa.service.SysUserService;
import com.cari.oa.util.Contants;
import com.cari.oa.util.StrUtils;
import com.cari.oa.util.Utils;

/**
* Title: ReqController
* Description:需求control
* Company:   cari 
* @author    hjx 
* @date      2013-3-12
*/
@Controller
@SessionAttributes({"username","usercnname"})
public class AllReqController extends BaseDownloadController {

	@Resource
	private ReqService reqService;
	@Resource
	private SysDictItemService sysDictItemService;
	@Resource
	private ReqTypeService reqTypeService;
	@Resource
	private CommentService commentService;
	@Resource
	private AttachmentService attachmentService;
	@Resource
	private ReqUserRefService reqUserRefService;
	@Resource
	private SysUserService sysUserService;
	@Resource
    private MarketProjectService marketProjectService;
	@Resource
	private NotificationService notificationService;
	
	public static final String MODULE_NAME = "REQ_MANAGE";
	
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        binder.registerCustomEditor(Date.class, new CustomDateEditor(df, false));
        binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
    }
	/**
	* Title: list
	* Description:分页查询需求数据
	* @author    hjx 
	* @date       2013-3-13 
	* @param title     标题
	* @param initiator 发起人
	* @param status    状态
	* @param reqType   需求类型
	* @param curPage
	* @param modelMap
	* @return
	*/
    @RequestMapping("allreq/list.do")
    public String list(@ModelAttribute("username") String username,String title, String cnName,String sortType, String status, String reqType, String project,String pName, Integer curPage, ModelMap modelMap) {       
    	if(curPage == null) curPage = 1;
        List<MarketProjectEntity> projects = marketProjectService.getAll();
    	//if(StrUtils.isEmpty(project) && projects !=null && projects.size()>0){
    	//	pName = projects.get(0).getName();
    	//	project = projects.get(0).getId();
    	//}
        long totalRecords = reqService.getCount(title, null, cnName, status, reqType, sortType, project);
        long totalPage = totalRecords / Contants.PAGE_SIZE + (totalRecords % Contants.PAGE_SIZE != 0 ? 1 : 0);
        List<ReqEntity> reqList = reqService.getPage(title,null, cnName, status, reqType,sortType, project, curPage, Contants.PAGE_SIZE);
        List<SysDictItemEntity> statusList = sysDictItemService.getItemsByGroupName("reqStatus");
        List<Map<String,String>> typeList = reqTypeService.getReqTypeNameAndPerson();
    	List<SysDictItemEntity> itemList =   sysDictItemService.getItemsByGroupName("reqStatus");
    	List<ReqTypeEntity> allReqType = reqTypeService.getAll();
    	List<SysDictItemEntity> sList =   sysDictItemService.getItemsByGroupName("reqResponsible"); 

    	for(ReqEntity cur : reqList)
	    {
	      	for(Map<String,String> map : typeList)
	      	{
	      		if(StrUtils.isNotEmpty(cur.getReqType()) && cur.getReqType().equals(map.get("typeId")))
	      		{   
	      			if(StrUtils.isEmpty(cur.getPrincipal())){
	        			cur.setTypeName(map.get("typeName"));
	        			cur.setPrincipal(map.get("cnName"));
	      			}else
	      			{
	      				cur.setPrincipal(cur.getPrincipal()+","+map.get("cnName"));
	      			}
	      		}
	      	}
	    }
		
        modelMap.addAttribute("sList", sList);
        modelMap.addAttribute("projects", projects);
        modelMap.addAttribute("allReqType", allReqType);
    	modelMap.addAttribute("itemList", itemList);
        modelMap.addAttribute("typeList", typeList);
        modelMap.addAttribute("statusList", statusList);
        modelMap.addAttribute("reqList", reqList);
        modelMap.addAttribute("curPage", curPage);
        modelMap.addAttribute("totalPage", totalPage);
        modelMap.addAttribute("totalRecords", totalRecords);
        modelMap.addAttribute("title", title);
        modelMap.addAttribute("cnName", cnName);
        modelMap.addAttribute("status", status);
        modelMap.addAttribute("reqType", reqType);
        modelMap.addAttribute("sortType", sortType);
        modelMap.addAttribute("project", project);
        modelMap.addAttribute("pName", pName);
        return "req/allreq/list";
    }
    
    /**
     * Title: enterView
     * Description:分发处理
     * @author     hjx 
     * @date       2013-3-13 
     * @param id
     * @param modelMap
     * @return
     */
     @RequestMapping(value = "allreq/handout.do")
     @ResponseBody
     public String handOut(@ModelAttribute("username") String username,@ModelAttribute("usercnname") String usercnname, String id,String values, ModelMap modelMap) {
     	ReqEntity req = reqService.getById(id);
     	List<AttachmentEntity> attList = attachmentService.getByObjectId(id);
     	
     	NotificationEntity noti = new NotificationEntity(req.getTitle()+"已经被分发", req.getTitle()+"已经被分发", username, usercnname, req.getInitiator(),req.getCnName(), 1);
    	notificationService.insert(noti);  //添加已被分发通知
     	
    	String[] reqTypeIds= values.split(",");
     	if(req.getStatus().equals("pass")){
	    	req.setStatus("pending");    //分发完成设置状态为待处理
	    	req.setRefuseReason(null);
			req.setRevokeReason(null);
			req.setNotPass(null);
	 		for(int i = 0 ;i < reqTypeIds.length ;i++)
	 		{
	 			req.setReqType(reqTypeIds[i]);
	 			if(i == 0)
	 				reqService.update(req);
	 			else
	 			{
	 				reqService.insert(req);
	 			}
	 			if(attList != null)
	 			{
	 				for(int j = 0;j < attList.size();j++)
	 				{
	 					AttachmentEntity att = attList.get(j);
	 					att.setObjectId(req.getId());
	 					if(i == 0)
	 		 				attachmentService.update(att);
	 		 			else
	 		 				attachmentService.insert(att);
	 				}
	 			}
	 		}
     	}
     	else
     	{
     		ReqEntity tempReq = new ReqEntity();
	 		for(int i = 0 ;i < reqTypeIds.length ;i++)
	 		{
	 			tempReq.setReqType(reqTypeIds[i]);
	 			tempReq.setTitle(req.getTitle());
	 			tempReq.setContent(req.getContent());
	 			tempReq.setInitiator(req.getInitiator());
	 			tempReq.setCnName(req.getCnName());
	 			tempReq.setStatus("pending");
	 			tempReq.setProject(req.getProject());
	 			tempReq.setStartStatus(req.getStartStatus());
	 			tempReq.setExpPerTime(req.getExpPerTime());
	 		    reqService.insert(tempReq);
	 			if(attList != null)
	 			{
	 				for(int j = 0;j < attList.size();j++)
	 				{
	 					AttachmentEntity att = attList.get(j);
	 					att.setObjectId(tempReq.getId());
	 		 		    attachmentService.insert(att);
	 				}
	 			}
	 		}
     	}
        return Utils.normalJsonResp();
     }
     
     /**
      * Title: enterView
      * Description:查看页面
      * @author     hjx 
      * @date       2013-3-13 
      * @param id
      * @param modelMap
      * @return
      */
      @RequestMapping(value = "allreq/view.do", method = RequestMethod.GET)
      public String enterView(String id,String qs, ModelMap modelMap) {
    	  ReqEntity req = reqService.getById(id);
          List<AttachmentEntity> attList = attachmentService.getByObjectId(id);
      	  List<CommentEntity> comList = commentService.getListByObjID(id,CommentService.CMT_REQ);
      	  List<SysDictItemEntity> itemList =   sysDictItemService.getItemsByGroupName("reqStatus"); 
          List<ReqTypeEntity> typeList = reqTypeService.getAll();
          modelMap.addAttribute("typeList", typeList);
          ReqUserRefEntity ruf = reqUserRefService.getByReqType(req.getReqType());
          if(ruf.getEnname()!=null)
          {
        	  SysUserEntity user =sysUserService.getByEnname(ruf.getEnname());
        	  if(user != null)
              modelMap.addAttribute("principal", user.getCnname());
          }
          List<SysDictItemEntity> sList = sysDictItemService.getItemsByGroupName("reqResponsible"); 
          modelMap.addAttribute("sList", sList);
          modelMap.addAttribute("itemList", itemList);
          modelMap.addAttribute("comList", comList);
          modelMap.addAttribute("attList", attList);
          modelMap.addAttribute("req", req);
          modelMap.addAttribute("qs", qs);
	      return "req/allreq/view";
      }
      
      /**
	  * Title: enterEdit
	  * Description:进入修改页面
	  * @author    hjx 
	  * @date       2013-3-13 
	  * @param id
	  * @param qs
	  * @param modelMap
	  * @return
	  */
      @RequestMapping(value = "allreq/edit.do", method = RequestMethod.GET)
      public String enterEdit(String id, String qs, ModelMap modelMap) {
	      	ReqEntity req = reqService.getById(id);
	      	List<AttachmentEntity> attList = attachmentService.getByObjectId(id);
	      	List<CommentEntity> comList = commentService.getListByObjID(id,CommentService.CMT_REQ);
	    	List<SysDictItemEntity> itemList =   sysDictItemService.getItemsByGroupName("reqStatus"); 
	    	ReqUserRefEntity ruf = reqUserRefService.getByReqType(req.getReqType());
	        List<ReqTypeEntity> typeList = reqTypeService.getAll();
	        if(ruf.getEnname()!=null)
	        {
	        	 SysUserEntity user =sysUserService.getByEnname(ruf.getEnname());
	        	 if(user != null)
	             modelMap.addAttribute("principal", user.getCnname());
	        }
	        List<SysDictItemEntity> sList = sysDictItemService.getItemsByGroupName("reqResponsible"); 
	        modelMap.addAttribute("sList", sList);
	        modelMap.addAttribute("typeList", typeList);
	    	modelMap.addAttribute("itemList", itemList);
	        modelMap.addAttribute("comList", comList);
	      	modelMap.addAttribute("attList", attList);
	        modelMap.addAttribute("req", req);
	        modelMap.addAttribute("qs", qs);
	        return "req/allreq/edit";
      }
      
      /**
       * Title: postEdit
       * Description:修改状态（拒绝或归档）
       * @author     hjx 
       * @date       2013-3-13 
       * @param username
       * @param req
       * @param result
       * @return
       */
       @RequestMapping(value = "allreq/edit.do", method = RequestMethod.POST)
       @ResponseBody
       public String postEdit(@ModelAttribute("username") String username, String reason,String status,String id, @Valid ReqEntity req, BindingResult result) {
           	req = reqService.getById(id);
           	req.setStatus(status);
            if(StrUtils.isNotEmpty(reason))
            {
            	req.setNotPass(reason);
            }
            reqService.update(req);
            SysOperLogController.addOperLog(username, MODULE_NAME, "修改需求状态" + req.getTitle());
            return Utils.normalJsonResp();
       }
}
